package cn.ckx.coding.common.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


@ApiModel(description = "分页")
@Data
public class PageResult<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 总记录数
     */
    @ApiModelProperty("总记录数")
    private Long totalCount;
    /**
     * 每页记录数
     */
    @ApiModelProperty("每页记录数")
    private Long pageSize;
    /**
     * 总页数
     */
    @ApiModelProperty("总页数")
    private Long totalPage;
    /**
     * 当前页数
     */
    @ApiModelProperty("当前页数")
    private Long currPage;
    /**
     * 列表数据
     */
    @ApiModelProperty("列表数据")
    private List<T> data;

    public static <T, R> PageResult<R> fromPage(IPage<T> page, Function<T, R> mapping) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setCurrPage(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setTotalCount(page.getTotal());
        pageResult.setTotalPage(page.getPages());
        pageResult.setData(page.getRecords()
                .stream()
                .map(mapping)
                .collect(Collectors.toList()));
        return pageResult;
    }

    public static <T, R> PageResult<R> fromPageResult(PageResult<T> page, Function<T, R> mapping) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setCurrPage(page.getCurrPage());
        pageResult.setPageSize(page.getPageSize());
        pageResult.setTotalCount(page.getTotalCount());
        pageResult.setTotalPage(page.getTotalPage());
        pageResult.setData(page.getData()
                .stream()
                .map(mapping)
                .collect(Collectors.toList()));
        return pageResult;
    }

    public static <R> PageResult<R> emptyResult() {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setCurrPage(1L);
        pageResult.setPageSize(10L);
        pageResult.setTotalCount(0L);
        pageResult.setTotalPage(0L);
        pageResult.setData(Collections.emptyList());
        return pageResult;
    }

}
